package com.qf.openapi.web.master.controller;

import cn.hutool.http.HttpResponse;
import com.qf.openapi.web.master.entity.User;
import com.qf.openapi.web.master.exception.UserException;
import com.qf.openapi.web.master.service.UserService;
import com.qf.openapi.web.master.utils.SessionKey;
import com.qf.openapi.web.master.vo.ResultVo;
import com.qf.openapi.web.master.vo.TableVo;
import com.qf.openapi.web.master.vo.UserRegistVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/user")
@Slf4j//引入日志对象
public class UserController {
    @Autowired
    private UserService userService;
    private String fileUploadPath = "E:\\JavaProject\\Idea\\File\\file\\";

    /*
     * 根据用户id查询用户
     * */
    @GetMapping("/get/{id}")
    public User getUser(@PathVariable("id") Integer id) {
        return userService.getUserById(id);
    }

    /* @RequestMapping("/login")
     public String login(String captcha, HttpSession session, String username, String password) {
         User user = userService.getUserByName(username);
         System.out.println(user);
         System.out.println(captcha);
         String captcha1 = (String) session.getAttribute("captcha");
         System.out.println(captcha1);
         if (captcha1.equals(captcha)) {
             if (username.equals(user.getName()) && password.equals(user.getPassword())) {
                 return "1";
             } else {
                 return "2";
             }
         } else {
             return "3";
         }

     }*/
    /*
     * 用户登录接口
     * return json数据
     * */
    @PostMapping("/login")
    public ResultVo login(String username, String password, String captcha, String switch1, HttpSession session, HttpServletResponse response) {
        //0.打印日志，把该web接口收到的参数打印到日志中
        log.debug("接口入参为：username={},password={},captcha={},", username, password, captcha);
        //1.校验验证码是否一致
        String sessionCaptcha = (String) session.getAttribute("captcha");
        if (sessionCaptcha != null) {
            if (!sessionCaptcha.equals(captcha)) {
                //直接返回错误信息
                ResultVo resultVo = ResultVo.error("验证码错误");
                return resultVo;
            }
        } else {
            ResultVo resultVo = ResultVo.error("服务器异常");
            return resultVo;
        }

        //2.查询数据库验证用户名和密码是否匹配
        //如何设计service层的方法
        //（1）要把处理业务逻辑所需要的参数都传给该方法
        //（2）返回值设计要满足web接口返回json数据的需求
        User user = userService.login(username, password);
        //根据user是否为null判断登陆状态返回json
        if (user == null) {
            //用户名密码错误导致的登陆失败
            return ResultVo.error("用户名密码错误");
        } else {
            //登陆成功
            ResultVo vo = ResultVo.ok();
            vo.put("data", user);
            session.setAttribute(SessionKey.user_Login_Session_Key, user);
            if (switch1 != null && "on".equals(switch1)) {
                Cookie cookie = new Cookie(SessionKey.user_AutoLogin_Cookie_Key, username + "-" + password);
                cookie.setPath("/");//路径
                cookie.setMaxAge(60 * 60 * 24 * 14);//有效期
                response.addCookie(cookie);//把cookie写回给浏览器
            }
            return vo;

        }
    }

    @PostMapping("/regist")
    public ResultVo regist(MultipartFile photo, UserRegistVo userRegistVo, String captcha, HttpSession session) throws IOException {
        //0.打印日志，把该web接口收到的参数打印到日志中
        log.debug("接口入参为：userRegistVo={},captcha={},photo={}", photo, userRegistVo, captcha);
        String sessionCaptcha = (String) session.getAttribute("captcha");
        if (captcha.equals(sessionCaptcha)) {
            boolean flag = userService.addUser(userRegistVo, photo);
            if (flag == true) {
                return ResultVo.ok();
            } else {
                return ResultVo.error("注册失败");
            }
        } else {
            return ResultVo.error("验证码错误");
        }
    }

    @GetMapping("/selectAll")
    public TableVo<User> selectAll(Integer page, Integer limit, String name, String sex, String birthday) {
        //0.打印日志，把该web接口收到的参数打印到日志中
        log.debug("接口入参为：page={},limit={}", page, limit);
        TableVo<User> tableVo = userService.selectAll(page, limit, name, sex, birthday);
        return tableVo;

    }

    @PostMapping("/add")
    public ResultVo insertUser(UserRegistVo userRegistVo) throws UserException {
        //0.打印日志，把该web接口收到的参数打印到日志中
        log.debug("接口入参为：userRegistVo={}", userRegistVo);
        boolean flag = userService.insertUser(userRegistVo);
        if (flag) {
            return ResultVo.ok();
        }
        return ResultVo.error("添加失败");
    }

    @PostMapping("/del")
    public ResultVo deleteUser(Integer[] ids) {
        //0.打印日志，把该web接口收到的参数打印到日志中
        log.debug("接口入参为: id={}", ids);
        boolean flag = userService.deleteUser(ids);
        if (flag) {
            return ResultVo.ok();
        }
        return ResultVo.error("删除失败");
    }

    @PostMapping("/update")
    public ResultVo updateUser(UserRegistVo userRegistVo) throws UserException {
        //0.打印日志，把该web接口收到的参数打印到日志中
        log.debug("接口入参为: userRegistVo={}", userRegistVo);
        boolean flag = userService.updateUser(userRegistVo);
        if (flag) {
            return ResultVo.ok();
        }
        return ResultVo.error("修改失败");
    }

    @RequestMapping("/pic")
    public void getUserPic(String picname, HttpServletRequest request, HttpServletResponse response) {
        log.debug("接口入参为：{}", picname);
        final String realPath = request.getServletContext().getRealPath("pic");
        // 根据传入的图片文件名，取服务器端指定路径加载图片并返回
        try {
            IOUtils.copy(new FileInputStream(realPath + File.separator + picname), response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/export")
    public ResultVo export() {
        String filename = userService.export();
        ResultVo ok = ResultVo.ok();
        ok.put("data", filename);
        return ok;
    }

    @RequestMapping("/currentUser")
    public ResultVo currentUser(HttpSession session) {
        // 从session中获取当前登录用户的信息
        User user = (User) session.getAttribute(SessionKey.user_Login_Session_Key);
        ResultVo vo = ResultVo.ok();
        vo.put("data", user);
        return vo;
    }

    /**
     * 获取当前登录用户头像
     *
     * @param filename
     * @param response
     * @throws IOException
     */
    @GetMapping("/photo")
    public void currentUserPhoto(String filename, HttpServletResponse response) throws IOException {
        String finalFilepath = fileUploadPath + filename;
        IOUtils.copy(new FileInputStream(finalFilepath), response.getOutputStream());
    }

    @PostMapping("/upload")
    public ResultVo uploadUser(MultipartFile file) throws IOException {
        userService.getListUser(file);
        return ResultVo.ok();
    }

}









